#include "sqliteDataProvider.h"

int insertmp3Info(sqlite3 **ppDb, id3filedata *mp3data,int isUpdate = 0)
{
	int strLen = 0;
	char *query;
	int rc = SQLITE_OK;
	strLen += strlen(mp3data->title) + strlen(mp3data->album) + strlen(mp3data->artist) + strlen(mp3data->filename) + strlen(mp3data->path) + 256;
	query = (char *) malloc (sizeof(char) * strLen);

	if(query == NULL)
	{
		writeLog(__func__,VSEVERE,SYSTEMLOGLEVEL,"Could not malloc %d for query!",strLen);
		exit(-1);
	}
	if (isUpdate == 0)
	{
		sprintf(query,"INSERT OR IGNORE INTO mp3Info values(%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")",mp3data->year,mp3data->title,mp3data->album,mp3data->artist,"English",mp3data->filename,mp3data->path);
	}
	else {
		sprintf(query,"UPDATE mp3Info SET songYear = %d, songTitle = \"%s\", songAlbum = \"%s\", songArtist = \"%s\" WHERE path = \"%s\")",mp3data->year,mp3data->title,mp3data->album,mp3data->artist,mp3data->path);
	}
	rc = sqliteExecute(*ppDb,query,0,0);
	return rc;
}

int initDatabase(char *filename,sqlite3 **ppDb)
{
	int rc = 0;
	char tempBuff[256] = {"\0"};
	rc = sqlite3_open(filename,ppDb);
	if (rc != SQLITE_OK)
	{
		printf("DB OPEN ERROR: %s\n",sqlite3_errmsg(*ppDb));
	}
	else
	{
		sprintf(tempBuff,"/usr/bin/sqlite3 %s < %s",filename,SQLFILE);
		//Assume that system() executes without errors
		system(tempBuff); 
	}
	return rc;
}

int deInit(sqlite3 *db)
{
	sqlite3_close(db);
}
int sqliteExecute(sqlite3 *db,const  char *query, int (*callback1)(void*,int,char**,char**),void * arg)
{
	char *errmsg;
	int rc;
	rc = sqlite3_exec(db,query, callback1, arg, &errmsg);
	if(rc != SQLITE_OK)
	{
		writeLog(__func__,VERROR,SYSTEMLOGLEVEL,"%s",errmsg);
		return -1;
	}
	return sqlite3_changes(db);
}

int getData(sqlite3 **db,char *query, arraycontainer *results)
{
	int rc = SQLITE_OK;
	const char *tail;
	sqlite3_stmt *res;
	if(sqlite3_prepare(*db,(const char *) query, 256, &res, &tail) != SQLITE_OK)
	{
		printf("Cant retrieve data: %s\n", sqlite3_errmsg(*db));
		return(-1);
	}
	else
	{
		results->dataarray = (char **) malloc(sizeof(char *) * MAXROWS);
		results->numelements = 0;
		while(sqlite3_step(res) == SQLITE_ROW)
		{
			results->dataarray[results->numelements] = strdup(sqlite3_column_text(res,0));	
			results->numelements++;
		}
		sqlite3_finalize(res);

	}
	return results->numelements;
}


//struct stat {
//    dev_t     st_dev;     /* ID of device containing file */
//    ino_t     st_ino;     /* inode number */
//    mode_t    st_mode;    /* protection */
//    nlink_t   st_nlink;   /* number of hard links */
//    uid_t     st_uid;     /* user ID of owner */
//    gid_t     st_gid;     /* group ID of owner */
//    dev_t     st_rdev;    /* device ID (if special file) */
//    off_t     st_size;    /* total size, in bytes */
//    blksize_t st_blksize; /* blocksize for file system I/O */
//    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
//    time_t    st_atime;   /* time of last access */
//    time_t    st_mtime;   /* time of last modification */
//    time_t    st_ctime;   /* time of last status change */
//}; 

//create table fileInfo ( 
//fileID INTEGER PRIMARY KEY AUTOINCREMENT,
//filePath TEXT,
//lastAccessed TEXT,
//uid	INTEGER,
//gid	INTEGER,
//fileSize INTEGER,
//permissions INTEGER,
//tagtype INTEGER );
//

int insertFileInfo(sqlite3 **db,struct stat *stbuf,char *filePath,int isUpdate = 0)
{
	int retVal = SQLITE_OK;
	char timeBuff[MICRO_BUFFER_SIZE] = {"\0"};
	char insertQuery[2048];
	getTimeStr(stbuf->st_atime,"%Y-%m-%d %H:%M:%S",timeBuff);
	sprintf(insertQuery,"INSERT OR IGNORE INTO fileInfo values(\"%s\",\"%s\",\"%s\",%d,%d,%d,%d)",filePath,strrchr(filePath,'/') + 1,timeBuff,(int)stbuf->st_uid,(int)stbuf->st_gid,(int)stbuf->st_size,(int)stbuf->st_mode);
	retVal = sqlite3_exec(*db,insertQuery,0,0,0);
	return retVal;
}

int insertjpgInfo(sqlite3 **ppDb, exiffiledata *exifdata,int isUpdate = 0)
{
	int strLen = 0;
	char *query;
	int rc = SQLITE_OK;
	strLen += strlen(exifdata->filename) + strlen(exifdata->colorspace) + strlen(exifdata->manufacturer) + strlen(exifdata->model) + strlen(exifdata->path) + 256;
	query = (char *) malloc (sizeof(char) * strLen);

	if(query == NULL)
	{
		writeLog(__func__,VSEVERE,SYSTEMLOGLEVEL,"Could not malloc %d for query!",strLen);
		exit(-1);
	}
	if (isUpdate == 0)
	{
		sprintf(query,"INSERT OR IGNORE INTO jpgInfo values(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")",exifdata->model,exifdata->manufacturer,exifdata->colorspace,exifdata->filename,exifdata->path);
	}
	else
	{
		sprintf(query,"UPDATE jpgInfo SET imageModel = \"%s\", imageManufacturer = \"%s\", imageColorSpace = \"%s\" WHERE path = \"%s\"",exifdata->model,exifdata->manufacturer,exifdata->colorspace,exifdata->path);
	}
	rc = sqliteExecute(*ppDb,query,0,0);
	return rc;
}

int insertCustomInfo(sqlite3 **ppDb,keyvaluecontainer *container,char *filepath,int isUpdate = 0)
{
	int i = 0;
	char *query;
	int rc = SQLITE_OK;
	query = (char *) malloc (sizeof(char) * BUFFER_SIZE );
	char *filename = strrchr(filepath,'/') + 1;

	if(query == NULL)
	{
		writeLog(__func__,VSEVERE,SYSTEMLOGLEVEL,"Could not malloc %d for query!",BUFFER_SIZE);
		exit(-1);
	}
	for (i = 0; i < container->numelements; i++)
	{
		if (isUpdate == 0)
		{
			sprintf(query,"INSERT OR IGNORE INTO customTagInfo values(\"%s\",\"%s\",\"%s\",\"%s\")",filepath,filename,container->keyarray[i],container->valuearray[i]);
		}
		else
		{
			sprintf(query,"UPDATE customTagInfo SET customKey = \"%s\", customValue = \"%s\" WHERE path = \"%s\" ",container->keyarray[i],container->valuearray[i],filepath);
		}
		rc = sqliteExecute(*ppDb,query,0,0);
	}
	return rc;

	
}
